import { Model, Document } from 'mongoose';

// 获取数据总条数
export const countTotal = (
  bussinessModel: Model<Document>,
  queryCondition = {},
) => {
  const count = bussinessModel.countDocuments(queryCondition);

  return count; 
}

// 通用分页方法，通过传入model和相关condition来进行分页并排序
export const limitPage = (
  bussinessModel: Model<Document>,
  pageSize: string,
  pageNum: string,
  queryCondition ={},
  sortCondition: IAnyObject
) => {
  if (!pageSize || !pageNum) {
    throw new Error('缺少必要的pageSize或pageNum参数');
  }

  const pageSizeParam = Number(pageSize);
  const pageNumParam = Number(pageNum);
  const skipCondition = (pageNumParam - 1) * pageSizeParam;
  let limitQuery = bussinessModel
    .find(queryCondition)
    .skip(skipCondition)
    .limit(pageSizeParam);

  // 排序
  if (sortCondition) {
    limitQuery = limitQuery.sort(sortCondition);
  }

  return limitQuery;
}